package com.jbt.mds.obdsdk

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.jbt.mds.obdsdk.extension.SPUtils
import com.jbt.mds.obdsdk.model.VITE_API_BASE_URL

import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.Response
import org.json.JSONObject
import java.io.IOException
import java.util.concurrent.TimeUnit


class LoginActivity:AppCompatActivity (){


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.login)





        findViewById<Button>(R.id.loginButton).setOnClickListener {
            val baseUrl = VITE_API_BASE_URL
            val useName = findViewById<EditText>(R.id.usernameEditText).text.toString()
            val pwdName = findViewById<EditText>(R.id.passwordEditText).text.toString()
            println(baseUrl+"baseaasd")

            val client = OkHttpClient.Builder()
                .callTimeout(1,TimeUnit.DAYS)
                .readTimeout(1,TimeUnit.DAYS)
                .writeTimeout(1,TimeUnit.DAYS)
                .build()

            val JSON: MediaType = "application/json; charset=utf-8".toMediaType()


            // JSON 数据
            val json = "{\"username\":\"$useName\",\"password\":\"$pwdName\"}"
            Log.i("11110","onFailurea  $json")

            val body: RequestBody = RequestBody.create( JSON,json)

            // 构建请求
            val request: Request = Request.Builder()
                .url(baseUrl+"/auth/login")
                .post(body)
                .build()
            


            // 异步发送请求
            client.newCall(request).enqueue(object : Callback {
                override fun onFailure(call: Call, e: IOException) {
                    e.printStackTrace()
                    runOnUiThread {
                        Toast.makeText(this@LoginActivity, "登录失败:${e.message?:""}", Toast.LENGTH_SHORT).show()
                    }
                }
                override fun onResponse(call: Call, response: Response) {
                    if(response.isSuccessful){
                        val json = response.body?.string()?.let { it1 -> JSONObject(it1) }
                        runOnUiThread {
                            if (json?.optInt("code", -1) == 200) {
                                Toast.makeText(this@LoginActivity, "成功登录", Toast.LENGTH_SHORT)
                                    .show()
                                val token = json.optJSONObject("data")?.optString("accessToken")
                                Log.i("11110","token  $token")
                                SPUtils.setString("token", token)
                                val intent = Intent()
                                intent.setClass(this@LoginActivity, DeviceInfoActivity::class.java)
                                startActivity(intent)
                                finish()
                            } else {
                                Toast.makeText(
                                    this@LoginActivity,
                                    "登录失败:${json?.optInt("code", -1)}",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    }
                }
            })
        }
    }
}